<?php

namespace app\admin\controller\goods;

use app\admin\model\activity\Tuangou;
use app\common\controller\Backend;
use app\admin\model\Comment;
use app\common\model\Category;
use think\Log;
use think\Request;

/**
 * 
 *
 * @icon fa fa-circle-o
 */

class Goods extends Backend
{
    
    /**
     * Goods模型对象
     * @var \app\admin\model\goods\Goods
     */
    protected $model = null;
    protected $commentModel=null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\goods\Goods;
        $this->commentModel = new Comment();
        $this->view->assign("flagList", (new Category())->getFlagList());
        $this->view->assign("actList", (new Tuangou())->where('status','>',0)->select());

    }
    
    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    public function pullTmallData(){
        $cateid=$this->request->param('ids',0);
        $result=$this->model->saveTmallGoods($cateid);
        Log::info('拉取数据 cateid'.$cateid.' - '.$result);
        if($result){
            $this->success();
        }else{
            $this->error('拉取数据失败');
        }
    }

    public function pullComment(){
        $cateid=31;
        $goods=$this->model->field('goodsid')->where(['selfCateId'=>$cateid])->select();
        foreach ($goods as $val){
            $result=$this->commentModel->pullTmallGoodsComment($val->goodsid);
        }
        if($result){
            $this->success();
        }
        $this->error('拉取数据失败');
    }

    public function setSellCount(){
        set_time_limit(0);
        $page=1;
        do{
            $goods=$this->model->field(['id,sales'])->order('id asc')->page($page,100)->select();
            if(empty($goods)) break;
            foreach ($goods as $row){
                $this->model->save(['sellCount'=>$this->parseSellCount($row['sales'])],['id'=>$row['id']]);
            }
            echo '已处理'.($page*100).'条'. "/n/r";
            ob_flush();
            $page++;
        }while(true);
        echo '已完成';
    }

    private function parseSellCount($str){
        $num=$str;
        if(preg_match('/\d+/',$str,$arr)){
            $num=$arr[0];
        }
        if(strpos($str,'万')){
            $num*=10000;
        }
        return $num;
    }




}
